//
//  WDCFContactChooseController.m
//  WDLoan
//
//  Created by gadmyth on 11/15/17.
//  Copyright © 2017 wanda. All rights reserved.
//

#import "WDPContactChooseController.h"
#import "WDPContactCell.h"
#import "ICEEMContacts.h"
#import "WDPContactDataModel.h"
#import "EMCheckContactsMobileRequestDataModel.h"
#import "EMCheckContactsMobileResponseDataModel.h"
#import "EMNavBarView.h"

static NSString *contactCellID = @"contactCellID";

#pragma mark - WDPUITableView

@interface WDPUITableView : UITableView

@property (nonatomic, strong) void (^reloadDataFinishBlock)(void);

@end

@implementation WDPUITableView

- (void)reloadData {
    
    [super reloadData];
    
    if (_reloadDataFinishBlock) {
        _reloadDataFinishBlock();
    }
}

@end

@interface UIControl(wdp)

@end

@implementation UIControl(wdp)

+(void)swapInstanceMethodWithClassName:(NSString*)className origSelName:(NSString*)origSelName newSelName:(NSString*)newSelName
{
    Class cls = NSClassFromString(className);
    
    SEL ori = NSSelectorFromString(origSelName);
    SEL new = NSSelectorFromString(newSelName);
    [self SwizzleInstanceMethodWithClass:cls origSel:ori newSel:new];
}

+(void)SwizzleInstanceMethodWithClass:(Class) c origSel:(SEL)origSEL newSel:(SEL)newSEL
{
    Method origMethod = class_getInstanceMethod(c, origSEL);
    Method newMethod = class_getInstanceMethod(c, newSEL);
    
    if (class_addMethod(c, origSEL, method_getImplementation(newMethod), method_getTypeEncoding(origMethod))) {
        class_replaceMethod(c, newSEL, method_getImplementation(origMethod), method_getTypeEncoding(newMethod));
    } else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

+ (void)load {
    
    NSString *originSel = NSStringFromSelector(@selector(setFrame:));
    NSString *newSel = NSStringFromSelector(@selector(wdp_setFrame:));
    NSString *className = NSStringFromClass(self.class);
    
    [self.class swapInstanceMethodWithClassName:className origSelName:originSel newSelName:newSel];
}

static CGFloat tableViewIndexLeft = 0.0f;
static CGFloat tableViewIndexWidth = 0.0f;

- (void)wdp_setFrame:(CGRect)frame {
    if ([self isKindOfClass:NSClassFromString(@"UITableViewIndex")]) {
        // setX
        if (tableViewIndexLeft == 0) {
            tableViewIndexLeft = frame.origin.x - 30;
        }
        if (tableViewIndexWidth == 0) {
            tableViewIndexWidth = frame.size.width/* + 30*/;
        }
        [self performSelector:@selector(setFont:) withObject:[UIFont systemFontOfSize:12.0f]];
        frame = CGRectMake(tableViewIndexLeft, frame.origin.y - 60.0f, tableViewIndexWidth, frame.size.height);
    }
    [self wdp_setFrame:frame];
}

@end

#pragma mark - WDPContactChooseController

@interface WDPContactChooseController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) WDPUITableView *tableView;
@property (nonatomic, strong) NSMutableArray<NSArray *> *contactSections;

@property (nonatomic, strong) UILocalizedIndexedCollation *collation;
@property (nonatomic, copy) NSIndexPath *selectedIndexPath;

@property (nonatomic, weak) UIView *tableViewIndex;
@property (nonatomic, strong) UILabel *tableViewIndexHighlightLabel;
@property (nonatomic, strong) NSString *currentIndexSectionTitle;

@end

@implementation WDPContactChooseController

+ (BOOL)isSingleton {
    return YES;
}

+ (BOOL)shouldPresent {
    return YES;
}

+ (BOOL)shouldDimiss {
    return YES;
}

- (BOOL)handleWillOpenUrlWithParams:(NSDictionary *)params {
    return YES;
}

-(void)leftTopAction:(id)sender {
    [ICENavigator queuePopAllUrlscheme];
    [super leftTopAction:sender];
    
    if (self.resultAction) {
        dispatch_delay_start(0.5);
        self.resultAction(nil, WDPGetContactUserCancel);
        dispatch_delay_end;
    }
}

- (BOOL)allowRightSlide {
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setLeftNavigationItemWithObject:[UIImage imageNamed:@"icon_nav_left_close"] right:@"完成" title:@"选择联系人"];
#warning todo: nav title
    // [self setLeftNavigationItemWithObject:nil right:nil title:@"选择联系人"];
    
//    [self updateTopRightButton];
    [self setupTableView];
//    [self updateViews];
    [self loadData];
    
    
}

- (void)setupTableView {
    _tableView = [[WDPUITableView alloc] init];
    
    if(isIphoneX){
        _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, VH(self.view) - 88.0-34.0);
    }
    else{
        _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, VH(self.view) - 64.0);
    }
    [self.view addSubview:_tableView];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 32)];
    backView.backgroundColor = ColorFromRGB(0xfff3d6);
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 9, 200, 14)];
    
    titleLabel.textColor = ColorFromRGB(0xf56300);
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.text = NSLocalizedString(@"请选择真实姓名的联系人", nil);
    
    [backView addSubview:titleLabel];
    
    _tableView.tableHeaderView = backView;
    
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.sectionIndexColor = ColorFromRGB(0x151515);
    _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:WDPContactCell.class forCellReuseIdentifier:contactCellID];
    _tableViewIndexHighlightLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _tableViewIndexHighlightLabel.font = FONT_PINGFANG_REGULAR_(12);
    _tableViewIndexHighlightLabel.textColor = [UIColor whiteColor];
    _tableViewIndexHighlightLabel.layer.masksToBounds = YES;
    _tableViewIndexHighlightLabel.backgroundColor = ColorFromRGB(0x00a1f4);
    _tableViewIndexHighlightLabel.textAlignment = NSTextAlignmentCenter;
    
    __weak typeof(self)weakSelf = self;
    _tableView.reloadDataFinishBlock = ^{
        Class cls = NSClassFromString(@"UITableViewIndex");
        for (UIView *sub in weakSelf.tableView.subviews) {
            if ([sub isKindOfClass:cls]) {
                weakSelf.tableViewIndex = sub;
                [weakSelf.tableViewIndex addSubview:weakSelf.tableViewIndexHighlightLabel];
                [weakSelf updateHighlightIndexSection];
                break;
            }
        }
    };
}

//- (void)updateViews {
//
//}

- (void)loadData {
    _collation = [UILocalizedIndexedCollation currentCollation];
    _contactSections = [NSMutableArray array];
    for (int i = 0; i < [_collation sectionTitles].count; i++) {
        NSMutableArray *array = [NSMutableArray array];
        [_contactSections addObject:array];
    }
    
    for (int i = 0; i < _contacts.count; i++) {
        WDPContactDataModel *m = _contacts[i];
        NSInteger sectionNumber = [_collation sectionForObject:m collationStringSelector:@selector(contactName)];
//        NSLog(@"title: %@", _collation.sectionTitles[sectionNumber]);
        NSMutableArray *section = (NSMutableArray *) _contactSections[sectionNumber];
        [section addObject:m];
    }
    [_tableView reloadData];
}

- (void)updateHighlightIndexSection {
    NSInteger firstVisibleSection = _tableView.indexPathsForVisibleRows.firstObject.section;
    NSString *sectionTitle = _collation.sectionTitles[firstVisibleSection];
    if ([_currentIndexSectionTitle isEqualToString:sectionTitle]) {
        return;
    }
    _currentIndexSectionTitle = sectionTitle;
    _tableViewIndexHighlightLabel.text = sectionTitle;
    [_tableViewIndexHighlightLabel sizeToFit];
    CGFloat side = fmax(VW(_tableViewIndexHighlightLabel), VH(_tableViewIndexHighlightLabel));
    CGFloat height = 14.6f;
    
    CGFloat middle = VH(_tableViewIndex) / 2;
    CGFloat realHeight = [_collation sectionTitles].count * height;
    CGFloat top = middle - realHeight / 2;
    CGFloat y = top + firstVisibleSection * height;
    
    [_tableViewIndexHighlightLabel modifySize:CGSizeMake(side, side)];
    _tableViewIndexHighlightLabel.layer.cornerRadius = side / 2;
    [_tableViewIndexHighlightLabel modifyY:y];
    [_tableViewIndexHighlightLabel alignToParent:WDAlignCenterHorizontal margin:0.0f];
}

//- (void)updateTopRightButton {
//    UIColor *color = (_selectedIndexPath || _selectedContact) ? [UIViewController getRightColor] : WDSD_99_COLOR;
//    if (self.navigationItem.rightBarButtonItems.count > 1) {
//        UIBarButtonItem *barButton = self.navigationItem.rightBarButtonItems[1];
//        UIButton *rightButton = (UIButton *) barButton.customView;
//        [rightButton setTitleColor:color forState:UIControlStateNormal];
//    }
//}

- (void)checkSelectStatus:(WDPContactDataModel *)model indexPath:(NSIndexPath *)indexPath {
    NSString *contactId = [self getContactId:model];
    if (!_selectedIndexPath && _selectedContact && [_selectedContact.Id isEqualToString:contactId]) {
        _selectedIndexPath = indexPath;
        
//        [self updateTopRightButton];
    }
}

- (NSString *)getContactId:(WDPContactDataModel *)model {
    NSString *contactId = [NSString stringWithFormat:@"<[%@]-[%@]>", model.name, model.originPhone];
    return contactId;
}

#pragma mark - UITableViewDelegate

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return _collation.sectionIndexTitles;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    NSInteger section = [_collation sectionForSectionIndexTitleAtIndex:index];
    return section;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54.0f;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _contactSections.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return _contactSections[section].count > 0 ? 35.0f : 0.0f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 35.0f)];
    header.backgroundColor = ColorFromRGB(0xf5f6f7);
    
    CGRect labelFrame = header.bounds;
    labelFrame.origin.x = 50.0f;
    
    NSString *sectionTitle = [UILocalizedIndexedCollation currentCollation].sectionIndexTitles[section];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.text = sectionTitle;
    label.font = FONT_PINGFANG_REGULAR_(14);
    label.textColor = ColorFromRGB(0x999999);
    label.frame = labelFrame;
    [header addSubview:label];
    
    return header;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _contactSections[section].count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WDPContactCell* cell = [tableView dequeueReusableCellWithIdentifier:contactCellID forIndexPath:indexPath];
    WDPContactDataModel *model = _contactSections[indexPath.section][indexPath.row];
    [cell updateViewsWithData:model];
    [cell updateViews];
    [self checkSelectStatus:model indexPath:indexPath];
    if (_selectedIndexPath == indexPath) {
        [cell select];
    }
    else {
        [cell deSelect];
    }
    [cell setBorder:WDViewBorderBottom Width:0.5f Color:ColorFromRGB(0xe1eaeb)];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // deSelect old
    if (_selectedIndexPath) {
        WDPContactCell *selectedCell = [tableView cellForRowAtIndexPath:_selectedIndexPath];
        if (selectedCell) {
            [selectedCell deSelect];
        }
    }
    // select new
    WDPContactCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell select];
    
    // update indexPath
    _selectedIndexPath = indexPath;
    
    WDPSelectedContactDataModel *selectedContact = nil;
    if (_selectedIndexPath) {
        WDPContactDataModel *selectContact = _contactSections[_selectedIndexPath.section][_selectedIndexPath.row];
        selectedContact = [WDPSelectedContactDataModel fromSuperClassObject:selectContact];
        
        selectedContact.Id = [selectedContact getContactId];
    }
    else {
        selectedContact = _selectedContact;
    }
    
    EMCheckContactsMobileRequestDataModel *dm = [EMCheckContactsMobileRequestDataModel new];
    
    dm.mobile = selectedContact.phone;
    dm.name = selectedContact.name;
    
    [dm requestSuccess:^(EMCheckContactsMobileResponseDataModel *response, NSString * _Nonnull message) {
        if ([response.status isEqualToString:@"SUCCESS"]){
                __block WDPContactsDataModel *contacts = [[WDPContactsDataModel alloc] init];
            contacts.contacts = (NSArray<WDPContactDataModel>*) self->_contacts;
                contacts.selected_contact = selectedContact;
            contacts.total_count = @(self->_totalCount);
                [self.navigationController popViewControllerAnimated:YES];
            
                if (self.resultAction) {
                    dispatch_delay_start(0.5f);
                   self.resultAction(contacts, WDPGetContactSuccess);
                    dispatch_delay_end;
                }
            
        }
    } failure:^(NSInteger errorCode, NSString * _Nonnull errorMessage, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self updateHighlightIndexSection];
}

@end
